package com.woyao.core.util;

import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.coremedia.iso.boxes.Container;
import com.coremedia.iso.boxes.TimeToSampleBox;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.authoring.tracks.CroppedTrack;
import com.squareup.picasso.Picasso;
import com.woyao.PlayVideoActivity;
import com.woyao.R;
import com.woyao.ShowImageActivity;
import com.woyao.WoyaoooApplication;
import com.woyao.core.FileUtil;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.KeyValue;
import com.woyao.core.service.AccountService;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import retrofit2.Call;

/**
 * Created by Administrator on 2016/9/20 0020.
 */
public class Common {
    public static final String serverURL = "http://vop.baidu.com/server_api";
    public static String token = "";
    public static final String apiKey = "6QhPko9rFNtwpKGgDO42yT7t";
    public static final String secretKey = "SwVg0shBD4ZQ97YoZCV0NxW8GevuuaY2";
    public static final String cuid = "9562650";

    public static final String defaultpic =  "http://www.woyaooo.com/static/images/icon175x175.jpeg";

    public static Integer SUCCESS_CODE = 666;
    public static Integer NOTHING_CODE = 0;

//
//https://blog.csdn.net/lxy_tap/article/details/74567282
//    MediaRecorderUtil mrUtil=new MediaRecorderUtil();
//mrUtil.recorderStart();
//    三、音视频合成
//
////aacPath录音的文件路径、mp4Path原视频路径、outPath合成之后输出的视频文件路径
//
//    boolean flag=Mp4ParseUtil.muxAacMp4(aacPath,mp4Path,outPath);
//    四、视频拼接
//
////mMp4List视频拼接的路径集合、outPath拼接成功的视频输出路径
//
//Mp4ParseUtil.appendMp4List(mMp4List,outPath);
//    大致就这样了
    public static synchronized void cutMp4(final long startTime, final long endTime, final String FilePath, final String WorkingPath, final String fileName){
        new Thread(new Runnable() {
            @Override
            public void run() {

                try{
                    //视频剪切
                    VideoClip videoClip= new VideoClip();//实例化VideoClip类
                    videoClip.setFilePath(FilePath);//设置被编辑视频的文件路径  FileUtil.getMediaDir()+"/test/laoma3.mp4"
                    videoClip.setWorkingPath(WorkingPath);//设置被编辑的视频输出路径  FileUtil.getMediaDir()
                    videoClip.setStartTime(startTime);//设置剪辑开始的时间
                    videoClip.setEndTime(endTime);//设置剪辑结束的时间
                    videoClip.setOutName(fileName);//设置输出的文件名称
                    videoClip.clip();//调用剪辑并保存视频文件方法（建议作为点击保存时的操作并加入等待对话框）

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // MediaStore (and general)

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }


        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static String getVideoSnapFile( String videoPath ,Context context) {

        Bitmap bm = retriveVideoFrameFromVideo( videoPath);

        String filename = videoPath.substring(videoPath.lastIndexOf("/")+1) +".png";

        return  "file://" + compressImage(bm , getDiskCachePath( context) +"/" + filename) ;
    }
    public static Bitmap retriveVideoFrameFromVideo(String videoPath)
    {
        Bitmap bitmap = null;
        MediaMetadataRetriever mediaMetadataRetriever = null;
        try
        {
            mediaMetadataRetriever = new MediaMetadataRetriever();
            if (Build.VERSION.SDK_INT >= 14)
                mediaMetadataRetriever.setDataSource(videoPath, new HashMap<String, String>());
            else
                mediaMetadataRetriever.setDataSource(videoPath);
            //   mediaMetadataRetriever.setDataSource(videoPath);
            bitmap = mediaMetadataRetriever.getFrameAtTime( ( 1000 + 1L), MediaMetadataRetriever.OPTION_CLOSEST_SYNC );
        }
        catch (Exception e)
        {
            e.printStackTrace();
//            throw new Throwable(
//                    "Exception in retriveVideoFrameFromVideo(String videoPath)"
//                            + e.getMessage());

        }
        finally
        {
            if (mediaMetadataRetriever != null)
            {
                mediaMetadataRetriever.release();
            }
        }
        return bitmap;
    }


    public static String compressImage(Bitmap bitmap, String filename) {
        if (bitmap == null ) {
            return defaultpic;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }

        File file = new File( filename);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
                return defaultpic;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return defaultpic;
        }
        bitmap.recycle();
        return file.getPath();
    }

    public static void swapEndian( String infile , String outfile){
        try{
            FileInputStream fs = new FileInputStream(infile);
            FileChannel fc = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int)fc.size());
            byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
            fc.read(byteBuffer);
            byteBuffer.flip();

            ShortBuffer buffer = byteBuffer.asShortBuffer();
            short[] shortArray = new short[(int)fc.size()/2];
            buffer.get(shortArray);

            byteBuffer.clear();
            byteBuffer.order(ByteOrder.BIG_ENDIAN);
            ShortBuffer shortOutputBuffer = byteBuffer.asShortBuffer();
            shortOutputBuffer.put(shortArray);

            FileChannel out = new FileOutputStream(outfile).getChannel();
            out.write(byteBuffer);
            out.close();

//            FileInputStream fs = new FileInputStream(infile);
//            FileChannel fc = fs.getChannel();
//
//            File file = new File(outfile);
//            FileOutputStream outStream = new FileOutputStream(file,false);
//
//            ByteBuffer buf = ByteBuffer.allocate(0x10000);
//            buf.order(ByteOrder.LITTLE_ENDIAN); // or ByteOrder.BIG_ENDIAN   LITTLE_ENDIAN
//            int len = 0;
//            while((len = fc.read(buf)) != -1){
//
//
//                outStream.write(buf.array(), 0, len);
//            }
//
//            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static void alert( Context context, String message){

        Dialog alertDialog = new AlertDialog.Builder(context).
                setTitle("信息").
                setMessage(message).
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).
                create();
        alertDialog.show();
    }

    public static String getDiskCachePath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            return context.getExternalCacheDir().getPath();
        } else {
            return context.getCacheDir().getPath();
        }
    }

    public static void uploadFile( Context context ,String filename,final String picturePath ){

        OSS oss = FileUtil.getOss( context );
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, picturePath);

// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.i("haiming","uploaded " + picturePath );
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                }
            }
        });

    }

    public static   List<KeyValue>   StringToKeyValue(ArrayList<String> hows) {
        List<KeyValue> ret = new ArrayList<KeyValue>() ;
        for (String howww : hows) {
            KeyValue kv = new KeyValue();
            kv.setNo(howww);
            kv.setName(howww);
            ret.add(kv);
        }
        return  ret;
    }



    public static   void   showSnack(Context ctt,View v, String content ) {
        Snackbar sb = Snackbar.make(v,content, Snackbar.LENGTH_SHORT);

        View view = sb.getView();
        view.setBackgroundColor(ContextCompat.getColor(ctt, R.color.colorPrimary));

        TextView tv = (TextView) view.findViewById(R.id.snackbar_text);
        tv.setTextColor(Color.WHITE);
        sb.show();
    }

    public static  void setProfileAttr( final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }


    public static  void setDemandAttr( final Integer id, final String att, final String content) {
        setDemandAttr(  id,  att,  content ,"");
    }

    public static  void setDemandAttr( final Integer id, final String att, final String content, final String act){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setDemandAttr(WoyaoooApplication.userId,id,att,content,act);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    public static  void setMemberAttr( final Integer id, final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setMemberAttr(WoyaoooApplication.userId,id,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }


    public static  void setOrgAttr( final Integer id, final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setOrgAttr(WoyaoooApplication.userId,id,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }


    public static  void setRelationAttr( final Integer id, final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setRelationAttr(WoyaoooApplication.userId,id,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    public static  void setContactAttr( final String id, final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setContactAttr(WoyaoooApplication.userId,id,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    public static String listToString(List<String> stringList){
        if (stringList==null) {
            return null;
        }
        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (String string : stringList) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(string);
        }
        return result.toString();
    }

    public static String KeyValueToNames(List<KeyValue> thelist){

        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (KeyValue theone : thelist) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(theone.getName());
        }
        return result.toString();
    }

    public static String KeyValueToNos(List<KeyValue> thelist){

        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (KeyValue theone : thelist) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(theone.getNo());
        }
        return result.toString();
    }

    private static Common ourInstance = new Common();

    public static Common getInstance() {
        return ourInstance;
    }

    private Common() {
    }

    public static void enableZoom(final Context context, ImageView demandPic, final String picpath ){
        GestureDetector.SimpleOnGestureListener getLis = new GestureDetector.SimpleOnGestureListener();
        final GestureDetector gestureDetector = new GestureDetector(context,getLis);

        gestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                return false;
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                Intent intent = new Intent();
                intent.setClass(context, ShowImageActivity.class);
                intent.putExtra("image",  picpath );
                context.startActivity(intent);
                return false;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                return false;
            }
        });


        demandPic.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

//                gestureDetector.onTouchEvent( event);
//                Intent intent = new Intent();
//                intent.setClass(ChanceActivity.this, ShowImageActivity.class);
//                intent.putExtra("image",  chance.getImage() );
//                startActivity(intent);
                return gestureDetector.onTouchEvent(event);
            }
        });
        demandPic.setClickable(true);
        demandPic.setFocusable(true);
        demandPic.setLongClickable(true);
    }

    public static void  showMedia( final Context context, final String onepic , LinearLayout pics  ){
        FrameLayout item = (FrameLayout) LayoutInflater.from(context).inflate(R.layout.image_item, null);
        ImageView imageView  = (ImageView)item.findViewById(R.id.pic);
        Button playBtn  = (Button)item.findViewById(R.id.video_play);

        String imagePath = "";
        if (onepic.endsWith( "mp4")) {
            imagePath = Common.getVideoSnapFile( onepic, context);
            playBtn.setVisibility( View.VISIBLE);
            playBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(context, PlayVideoActivity.class);
                    intent.putExtra("path", onepic );
                    context.startActivity(intent );
                }
            });
        }else {
            imagePath =  onepic;
            Common.enableZoom(context,imageView,onepic);
            playBtn.setVisibility( View.GONE);
        }

        Picasso.with(context)
                .load(imagePath)
                .into(imageView );
        pics.addView(item);
    }

}
